import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/layout'
import { Message } from 'element-ui';
import { getPermission } from "./check"

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index'), hidden: true
  },
  {
    path: '/',
    redirect: '/home',
    component: Layout, 
    name: 'index',
    children: [
      {
        path: '/home',
        name: 'home',
        component: () => import('@/views/home.vue'),
        meta: { title: 'home', icon: 'example' },
      },
      {
        path: '/system',
        name: 'system',
        component: () => import('@/views/system/info'),
        meta: { title: '系统管理' },
      },
      {
        path: '/table',
        name: 'table',
        component: () => import('@/views/table/index'),
        meta: { title: '列表' },
      },
      {
        path: '/from',
        name: 'from',
        component: () => import('@/views/from/index'),
        meta: { title: '表单' },
      }
    ]
  }
]

const router = new VueRouter({
  base: process.env.BASE_URL,
  routes: routes
})

router.beforeEach((to, from, next) => {
  // 用户信息 用来校验token等操作
  const isAuthenticated = localStorage.getItem('userInfo');
  // console.log('to',to);
  if (to.path !== '/login' && !isAuthenticated) {
    next({ path: '/login' })
    // 用户信息不存在重新登录
  } else {
    // 用户信息存在 权限判断
    if (getPermission(to.path)) {
      next();
    } else {
      Message.closeAll();
      Message.error('暂无权限')
      next({ path: '/login' })
    }
  }
});

export {
  router,
  routes,
};